package com.duniptech.soa.modeling;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.w3c.dom.Element;

import com.duniptech.soa.adapter.CoupledDevsJava;

import GenCol.entity;
/**
 * @author  jlrisco
 */
public class AtomicDevsJava extends AtomicBase implements AtomicInterface {
	private genDevs.modeling.atomic model;
	
	public AtomicDevsJava(Element xmlAtomic) throws Exception {
		super(xmlAtomic);
		Object modelAux = null;
		String nodeName = xmlAtomic.getNodeName();
		if(nodeName.equals("coupled"))
			modelAux = new CoupledDevsJava((genDevs.modeling.digraph)Class.forName(xmlAtomic.getAttribute("class")).newInstance());
		else if(nodeName.equals("atomic"))
			modelAux = Class.forName(xmlAtomic.getAttribute("class")).newInstance();
		this.model = (genDevs.modeling.atomic)modelAux;
	}
	
	public void initialize() {
		model.initialize();
	}
	
	public double ta() {
		double sigmaAux = model.ta();
		if(sigmaAux>=genDevs.modeling.DevsInterface.INFINITY)
			return Double.POSITIVE_INFINITY;
		return sigmaAux;
	}

	public void deltint() {
		model.deltint();
	}

	public void deltext(double e) {
		genDevs.modeling.message msg = buildMessage();
		model.deltext(e, msg);
	}

	public void deltcon(double e) {
		genDevs.modeling.message msg = buildMessage();
		model.deltcon(e, msg);
	}

	public void lambda() {
		genDevs.modeling.message msg = model.out();
		genDevs.modeling.ContentIteratorInterface itr = msg.mIterator();
		while(itr.hasNext()) {
			genDevs.modeling.ContentInterface devsJavaPort = itr.next();
			Port port = output.get(devsJavaPort.getPortName());
			if(port!=null) {
				port.addValue(devsJavaPort.getValue());
			}
		}
	}
	
	public genDevs.modeling.message buildMessage() {
		genDevs.modeling.message msg = new genDevs.modeling.message();
		Map<String, Port> ports = input.ports;
		Iterator<String> itr = ports.keySet().iterator();
		while(itr.hasNext()) {
			String portName = itr.next();
			Set<Object> values = ports.get(portName).getValues();
			for(Object value : values) {
				genDevs.modeling.content con = model.makeContent(portName, (entity)value);
				msg.add(con);
			}
		}
		return msg;
	}
}
